package com.common.widget.form;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import com.common.R;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 用于弹出系统时间dialog
 *
 */
public class FormDateView extends RelativeLayout implements View.OnClickListener {

    private String mTagString;
    private String mTextString;
    private Boolean mShowDivider;

    private LinearLayout mFormContentView;

    private TextView mTagTextView;
    private TextView mDateTextView;
    private View mDividerView;

    private int mDateTimeType;

    private TimePicker mTimePicker;
    private DatePicker mDatePicker;
    View mTargetView = null;
    private String  mDialogTitle;

    private SimpleDateFormat sdft = null;
    private boolean mForm_arrow_iconIshow;
    private ImageView mForm_arrow_icon;
    private ImageView mForm_icon;
    private int mIconResource;

    public FormDateView(Context context) {
        super(context);
        init(null, 0);
    }

    public FormDateView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0);
    }

    public FormDateView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
    }

    private void init(AttributeSet attrs, int defStyle) {

        // Load attributes
        final TypedArray a = getContext().obtainStyledAttributes(
                attrs, R.styleable.FormView, defStyle, 0);

        mTagString = a.getString(
                R.styleable.FormView_form_tag);
        mTextString = a.getString(
                R.styleable.FormView_form_text);
        mShowDivider = a.getBoolean(
                R.styleable.FormView_form_divider, true);
        mForm_arrow_iconIshow = a.getBoolean(
                R.styleable.FormView_form_has_arrow,true);
        mIconResource=a.getResourceId(R.styleable.FormView_form_icon,-1);
        mDateTimeType = a.getInt(R.styleable.FormView_form_datetime_picker_type, DATE_TYPE);
        a.recycle();

        LayoutInflater.from(getContext()).inflate(R.layout.view_form_date_view, this, true);
        mFormContentView = (LinearLayout) findViewById(R.id.form_content);
        mTagTextView = (TextView) findViewById(R.id.form_tag);
        mDateTextView = (TextView) findViewById(R.id.form_date);
        mDividerView = findViewById(R.id.form_divider);
        mForm_icon = (ImageView)findViewById(R.id.form_icon);
        mForm_arrow_icon = (ImageView)findViewById(R.id.form_arrow);
        if(mForm_arrow_iconIshow && mIconResource != -1){
            mForm_icon.setImageResource(mIconResource);
            mForm_icon.setVisibility(View.VISIBLE);
            mForm_arrow_icon.setVisibility(View.VISIBLE);
         }
        if (mTagString != null) {
            mTagTextView.setText(mTagString);
        }
        if (mTextString != null) {
            mDateTextView.setText(mTextString);
        }

        mTagTextView.setTextColor(getResources().getColor(R.color.form_item_tag_text_color));

        mDividerView.setVisibility(mShowDivider ? View.VISIBLE : View.GONE);

        mFormContentView.setOnClickListener(this);
        Calendar calendar = Calendar.getInstance();
        Date nowDate = calendar.getTime();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDay = calendar.get(Calendar.DAY_OF_MONTH);
        mHour = calendar.get(Calendar.HOUR_OF_DAY);
        mMinutes = calendar.get(Calendar.MINUTE);

        switch(mDateTimeType){
            case DATE_TYPE:
                sdft =  new SimpleDateFormat("yyyy-MM-dd");
                mDialogTitle = "请选择日期";
                mTargetView  = LayoutInflater.from(getContext()).inflate(R.layout.view_picker_date,null);
                mDatePicker = (DatePicker)mTargetView.findViewById(R.id.datePicker);
                mDate = sdft.format(nowDate);
                break;
            case TIME_TYPE:
                sdft =  new SimpleDateFormat("HH:mm");
                mDialogTitle = "请选择时间";
                mTargetView =  LayoutInflater.from(getContext()).inflate(R.layout.view_picker_time,null);
                mTimePicker = (TimePicker)mTargetView.findViewById(R.id.timePicker);
                mTimePicker.setOnTimeChangedListener(timePickerChangeListener);
                mTimePicker.setIs24HourView(true);
                mTime = sdft.format(nowDate);
                break;
            case DATETIME_TYPE:
                sdft =  new SimpleDateFormat("yyyy-MM-dd HH:mm");
                SimpleDateFormat sdft1 = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat sdft2 = new SimpleDateFormat("HH:mm");
                mDialogTitle = "请选择日期时间";
                mTargetView =  LayoutInflater.from(getContext()).inflate(R.layout.view_picker_date_time,null);
                mDatePicker = (DatePicker)mTargetView.findViewById(R.id.datePicker);
                mTimePicker = (TimePicker)mTargetView.findViewById(R.id.timePicker);
                mTimePicker.setIs24HourView(true);
                mTimePicker.setOnTimeChangedListener(timePickerChangeListener);
                mDate = sdft1.format(nowDate);
                mTime = sdft2.format(nowDate);
                break;
        }
        mDateTextView.setText(sdft.format(nowDate));
    }

    private View getTargetView(){
        switch(mDateTimeType){
            case DATE_TYPE:
                mTargetView  = LayoutInflater.from(getContext()).inflate(R.layout.view_picker_date,null);
                mDatePicker = (DatePicker)mTargetView.findViewById(R.id.datePicker);
                break;
            case TIME_TYPE:
                mTargetView =  LayoutInflater.from(getContext()).inflate(R.layout.view_picker_time,null);
                mTimePicker = (TimePicker)mTargetView.findViewById(R.id.timePicker);
                mTimePicker.setOnTimeChangedListener(timePickerChangeListener);
                mTimePicker.setIs24HourView(true);
                break;
            case DATETIME_TYPE:
                mTargetView =  LayoutInflater.from(getContext()).inflate(R.layout.view_picker_date_time,null);
                mDatePicker = (DatePicker)mTargetView.findViewById(R.id.datePicker);
                mTimePicker = (TimePicker)mTargetView.findViewById(R.id.timePicker);
                mTimePicker.setOnTimeChangedListener(timePickerChangeListener);
                mTimePicker.setIs24HourView(true);
                break;
        }
        return mTargetView;
    }

    private String mTime;
    private String mDate;

    private  TimePicker.OnTimeChangedListener timePickerChangeListener = new TimePicker.OnTimeChangedListener(){

        @Override
        public void onTimeChanged(TimePicker timePicker, int hourOfDay, int minute) {
            mTime = new StringBuilder()
                    .append(pad(hourOfDay)).append(":")
                    .append(pad(minute)).toString();

        }
    };

    private DatePicker.OnDateChangedListener datePickerChangeListener = new DatePicker.OnDateChangedListener(){

        @Override
        public void onDateChanged(DatePicker datePicker, int year, int month, int day) {
            mDate = new StringBuilder().append(year).append("-").append(pad(month + 1)).append("-").append(pad(day)).toString();

        }
    };

    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }

    private int mYear;
    private int mMonth;
    private int mDay;
    private int mHour;
    private int mMinutes;


    public void setTag(String tag) {
        mTagTextView.setText(tag);
    }

    public void setDateText(String text) {
        mDateTextView.setText(text);
        if(TextUtils.isEmpty(text)){
            return;
        }
        Calendar calendar = Calendar.getInstance();
        try{
            calendar.setTime(sdft.parse(text));
            mYear = calendar.get(Calendar.YEAR);
            mMonth = calendar.get(Calendar.MONTH);
            mDay = calendar.get(Calendar.DAY_OF_MONTH);
            mHour = calendar.get(Calendar.HOUR_OF_DAY);
            mMinutes = calendar.get(Calendar.MINUTE);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public void setDefaultDate(){

    }

    public String getDateText() {
        return mDateTextView.getText().toString();
    }

    private static final int DATE_TYPE = 0;
    private static final int TIME_TYPE = DATE_TYPE + 1;
    private static final int DATETIME_TYPE = TIME_TYPE + 1;

    @Override
    public void onClick(View view) {


        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle(mDialogTitle);
        if (mTargetView.getParent() == null) {
            builder.setView(mTargetView);
        } else {
            ((ViewGroup)mTargetView.getParent()).removeAllViews();
            mTargetView = getTargetView();
            builder.setView(mTargetView);
        }

        switch(mDateTimeType){
            case DATETIME_TYPE:
                mTimePicker.setCurrentHour(mHour);
                mTimePicker.setCurrentMinute(mMinutes);
            case DATE_TYPE:
                mDatePicker.init(mYear,mMonth,mDay,datePickerChangeListener);
                break;
            case TIME_TYPE:
                mTimePicker.setCurrentHour(mHour);
                mTimePicker.setCurrentMinute(mMinutes);
                break;
        }

        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                switch(mDateTimeType){
                    case DATE_TYPE:
                        setDateText(mDate);
                        break;
                    case TIME_TYPE:
                        setDateText(mTime);
                        break;
                    case DATETIME_TYPE:
                        setDateText(mDate+" "+mTime);
                        break;
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.show();
    }
}
